package com.huyun.web.concurrency.threadPoolExecutor;

import com.huyun.web.FutureTest.WaterMarkTask;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * @author huyunqiang
 * @Date 2019/4/16 22:25
 */

/**
 * 线程池的测试和使用
 */
public class Test {
    public static void main(String[] args) {
        // 使用ThreadPoolExecutor 创建线程池
//        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
//                new ArrayBlockingQueue<Runnable>(5));
       //使用Executor 的静态方法创建线程池
        ExecutorService service = Executors.newCachedThreadPool();
        ExecutorService service1 = Executors.newFixedThreadPool(5);
        ExecutorService service2 = Executors.newSingleThreadExecutor();
        ExecutorService service3 = Executors.newScheduledThreadPool(1);

        ExecutorService executor = newFixedThreadPool(15);
        // 每次有5个线程去执行任务
        for(int i=0;i<15;i++){
            WaterMarkTask myTask = new WaterMarkTask(i);
            service1.execute(myTask);
        }
        executor.shutdown();

        //不使用线程池 创建了15个线程去执行
//        for(int i= 0;i<15;i++){
//            MyTask myTask = new MyTask(i);
//            Thread thread = new Thread(myTask);
//            thread.start();
//            System.out.println(thread.getName());
//        }

    }

    /**
     * 创建一个固定长度的线城池
     * @param nThreads
     * @return
     *
     * 第一个参数：线程池的大小
     * 第二个参数：线程池的最大线程数
     * 第三个参数：线程空闲的等待时间 线程的关闭是需要消耗资源的
     *    但是默认该参数只有在 线程数大于corePoolSize时才会生效
     * 第四个参数： 第三个参数的单位
     * 第五个采纳数： 等待执行任务的阻塞队列
     *
     *
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    }

    /**
     * 创建一个可缓存的线程池
     * @return
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
    }
}


class MyTask implements Runnable {
    private int taskNum;

    public MyTask(int num) {
        this.taskNum = num;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"正在执行task "+taskNum);
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"task "+taskNum+"执行完毕");
    }
}
